<?php

namespace app\admin\controller\product;

use app\common\controller\Backend;

// 商品分类管理
class Type extends Backend
{
    // 快速搜索
    protected $searchFields = ['id','name'];

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();

        $this->model = model('Product.Type');
    }

    // 商品分类列表
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        if($this->request->isAjax())
        {
            if ($this->request->request('keyField')) 
            {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    // 新增商品分类
    public function add()
    {
        if($this->request->isPost())
        {
            $params = $this->request->param('row/a');

            if($params)
            {
                // 封装新增的数据
                $data = [
                    'name' => $params['name'],
                    'weigh' => $params['weigh'],
                    'thumb' => $params['thumb']
                ];

                // 插入数据库
                $result = $this->model->validate('common/Product/Type')->save($data);

                if($result === FALSE)
                {
                    $thumb = ltrim($data['thumb'],'/');

                    @is_file($thumb) && @unlink($thumb);

                    $this->error($this->model->getError());
                    exit;
                }else
                {
                    $this->success();
                    exit;
                }
            }
        }

        $weigh = $this->model->max('weigh');
        $weigh = $weigh > 0 ? ++$weigh : 1;

        $this->assign('weigh', $weigh);

        return $this->view->fetch();
    }

    // 编辑商品分类
    public function edit($ids = null)
    {
        $row = $this->model->find($ids);

        // 找不到数据返回错误信息
        if(!$row)
        {
            $this->error(__('该分类不存在，请重新选择'));
            exit;
        }

        if($this->request->isPost())
        {
            $params = $this->request->post('row/a');

            if($params)
            {
                // 封装更新数组
                $data = [
                    'id' => $ids,
                    'name' => $params['name'],
                    'weigh' => $params['weigh'],
                    'thumb' => $params['thumb']
                ];

                $result = $this->model->validate('common/Product/Type')->isUpdate(true)->save($data);

                if($result === FALSE)
                {
                    if($data['thumb'] != $row['thumb'])
                    {
                        // 左边的/去掉
                        $thumb = ltrim($data['thumb'],'/'); 
                        @is_file($thumb) && @unlink($thumb);
                    }

                    $this->error($this->model->getError());
                    exit;
                }else
                {
                    // 如果图片名称不一样时说明有更新图片，需要把旧图片删除
                    if($data['thumb'] != $row['thumb'])
                    {
                        $thumb = ltrim($row['thumb'],'/');
                        @is_file('.'.$row['thumb']) && @unlink('.'.$row['thumb']);
                    }

                    $this->success();
                    exit;
                }
            }
        }

        $this->assign('row', $row);

        return $this->view->fetch();
    }

    // 删除商品分类
    public function del($ids = null)
    {
        $list = $this->model->select($ids);

        if(empty($list))
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $result = $this->model->destroy($ids);

        if($result === FALSE)
        {
            $this->error($this->model->getError());
            exit;
        }else
        {
            $thumb = array_column($list, "thumb");
            $thumb = array_filter($thumb);
            $thumb = array_unique($thumb);

            if(!empty($thumb))
            {
                foreach($thumb as $item)
                {
                    $item = ltrim($item,'/');
                    @is_file($item) && @unlink($item);
                }
            }
            
            $this->success();
            exit;
        }
    }
}